package com.ibm.ems.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.ems.dto.*;
import com.ibm.ems.dao.PollingDAO;

;
/**
 * Servlet implementation class EventsPoll
 */
public class PollUpdaterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PollUpdaterServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void pollEvents(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			ClassNotFoundException, SQLException {

		Map<String, String[]> votes = request.getParameterMap();
		Set<String> keySet = votes.keySet();
		UserBean user = new UserBean();
		String userName = "userName";
		user.setUserName(userName);
		PollingBean poll = new PollingBean();
		PollingDAO PollDB = new PollingDAO();
		ArrayList<PollingBean> pollList = new ArrayList<PollingBean>();

		for (Iterator<String> iterator = keySet.iterator(); iterator.hasNext();) {

			String key = (String) iterator.next();
			String vote = votes.get(key)[0].toLowerCase();
			poll.setTopicId(key);
			poll.setUserName(userName);
			poll.setVote((vote.equals("yes")));
			pollList.add(poll);
			// PollDB.commitPolling(poll);
		}
		PollDB.commitPolling(pollList);

		// update the tables
		PrintWriter out = response.getWriter();
		out.println("tables updated");

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			pollEvents(request, response);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			pollEvents(request, response);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
